package com.yanyu.space.common.log;

import ch.qos.logback.core.UnsynchronizedAppenderBase;
import ch.qos.logback.core.encoder.Encoder;
import ch.qos.logback.core.spi.DeferredProcessingAware;
import ch.qos.logback.core.status.ErrorStatus;
import com.yanyu.space.common.log.handler.LogFactory;
import com.yanyu.space.common.log.message.LogMessage;

/**
 * @author yanyu
 */
public class LogKafkaAppender<E> extends UnsynchronizedAppenderBase<E> {

    protected Encoder<E> encoder;

    @Override
    protected void append(E event) {
        if (!isStarted()) {
            return;
        }
        try {
            if (event instanceof DeferredProcessingAware) {
                ((DeferredProcessingAware) event).prepareForDeferredProcessing();
            }

            byte[] byteArray = this.encoder.encode(event);
            LogFactory.getInstance().submit(new LogMessage(byteArray));
        } catch (Exception ioe) {
            this.started = false;
            addStatus(new ErrorStatus("IO failure in appender", this, ioe));
        }
    }

    @Override
    public void start() {
        super.start();
    }


    public void setEncoder(Encoder<E> encoder) {
        this.encoder = encoder;
    }
}
